package com.company;

import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class EchoServer {

    private static class ClientThread implements Runnable {
        static long threadId = 0;
        private Socket client;
        private Scanner scan;
        private PrintStream out;
        public final long id;

        public ClientThread(Socket client) throws Exception {
            this.client = client;
            this.scan = new Scanner(client.getInputStream());
            this.scan.useDelimiter("\n");
            this.out = new PrintStream(this.client.getOutputStream());
            this.id = ClientThread.threadId ++;
        }

        public boolean flag = true;

        @Override
        public void run() {
            while(this.flag) {
                if (scan.hasNext()) {
                    String val = scan.next().trim();
                    if (val.equalsIgnoreCase("Bye bye")) {
                        this.out.println("bye bye.-- from serve");
                        flag = false;
                    } else {
                        System.out.println("Server[" + this.id + "] get string[" + val + "]");
                        this.out.println("[ECHO]" + val);
                    }
                }
            }
            try {
                this.scan.close();
                this.out.close();
                this.client.close();
            } catch (Exception err) {
                err.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws Exception {
        ServerSocket socket = new ServerSocket(9999);
        System.out.println("waiting for client response----");
        Socket client = socket.accept();
        new Thread(new EchoServer.ClientThread(client)).start();
        socket.close();
    }
}
